# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

from pylons import request, tmpl_context as c
from pylons.controllers.util import redirect
from pylons.decorators import rest

from chowa.lib.base import BaseController, render, Session


class MergerDruidController(BaseController):
    def select(self):
        ids = request.params.get('ids').split('.')
        c.records = self._get_records(ids)
        return render('/druids/merger/select.html')

    @rest.restrict('POST')
    def select_one(self):
        ids = request.POST.getall('ids')
        c.records = self._get_records(ids)
        c.referer = request.params.get('referer')
        return render('/druids/merger/select_one.html')
    
    @rest.restrict('POST')
    def confirm(self):
        ids = request.POST.getall('ids')
        record_id = request.POST.get('record_id')
        c.records = self._get_records(ids)
        c.one_record = Session.query(self.__model__).get(record_id)
        if request.POST.get('confirm'):
            self._merge(ids, record_id)
            return redirect(request.params.get('referer'))
        return render('/druids/merger/confirm.html')
    
    def _get_records(self, ids):
        query = Session.query(self.__model__)
        return query.filter(self.__model__.id.in_(ids)).all()
    
    def _merge(self, ids, record_id):
        model = self.__model__
        deps = model.__mapper__._dependency_processors
        for dep in deps:
            columns = [pair[0] for pair in dep.prop.local_remote_pairs]
            for column in columns:
                query = column.table.update() \
                    .where(column.in_(ids)) \
                    .values({column: record_id})
                Session.execute(query)
        query = Session.query(model).filter(model.id.in_(ids)) \
                                    .filter(model.id != record_id)
        query.delete(synchronize_session=False)
        Session.commit()
